#!/usr/bin/env node

const express = require("express");
const path = require("path");
const fs = require("fs");
const os = require("os");
const _ = require("lodash");
const { createProxyMiddleware } = require("http-proxy-middleware");
const logFile = path.join(os.homedir(), '.xn_history', '.xn_proxy_history');

let port = 4000;
let pathRewrite;
const params = process.argv.slice(2);
const line = params.join(' ');
let index = params.indexOf('-p') === -1 ? params.indexOf('--port') : params.indexOf('-p');
if (index > -1 && params[index + 1]) {
    port = params[index + 1];
    params.splice(index, 2);
}
index = params.indexOf('-w') === -1 ? params.indexOf('--pathRewrite') : params.indexOf('-w');
if (index > -1 && params[index + 1]) {
    pathRewrite = params[index + 1];
    params.splice(index, 2);
}
const param = params[0];
if (param === '-h' || param === '--help' || !param) {
    console.log('');
    console.log('xproxy api@url');
    console.log('');
    console.log('   -h|--help: show help');
    console.log('   -l|--list: show history list');
    console.log('   -p|--port: set port for server');
    console.log('   -w|--pathRewrite: for rewrite path e.g: xx:yy');
    console.log('   xproxy api@http://localhost:5000 -w api:');
    console.log('   notifyEntry@http://localhost:1112/xs_os/api/notify/notifyEntry');
    process.exit(0);
}
if (param === '-l' || param === '--list') {
    console.log(fs.existsSync(logFile) ? fs.readFileSync(logFile, 'utf-8') : '');
    process.exit(0);
}
let list = param.split('@');
if (!list[1]) {
    console.log('param must be api@url');
    process.exit(0);
}
const format = p => p[0] === '/' ? p : `/${p}`;
const api = format(list[0]);
const target = list[1];
pathRewrite = pathRewrite ? {[format(pathRewrite.split(':')[0])]: format(pathRewrite.split(':')[1])} : {[`^${api}`]: `/`};
console.log({
    api,
    target,
    changeOrigin: true,
    pathRewrite,
});
const app = express();

app.use(
  '/',
  createProxyMiddleware({
    target,
    changeOrigin: true,
    pathRewrite,
  })
);

list = fs.existsSync(logFile) ? fs.readFileSync(logFile, 'utf-8').split(/\n/) : [];
list = _.reverse(list);
list.unshift(`xproxy ${line}`);
list = _.uniq(list);
list = _.reverse(list);
fs.writeFileSync(logFile, list.join('\n'), 'utf-8');

app.listen(port);
console.log(`http://localhost:${port}${api} -> ${target}`);